/*
 * FilePath     : \vite.config.ts
 * Author       : SJZ
 * Date         : 2025-03-12 19:28
 * LastEditors  : SJZ
 * LastEditTime : 2025-03-12 22:24
 * Description  :  项目配置文件
 * CodeIterationRecord:
 */

import { fileURLToPath, URL } from "node:url";

import legacy from "@vitejs/plugin-legacy";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import { defineConfig, loadEnv } from "vite";
import topLevelAwait from "vite-plugin-top-level-await";
import VueDevTools from "vite-plugin-vue-devtools";
import { VueHooksPlusResolver } from "@vue-hooks-plus/resolvers";
import UnoCss from "unocss/vite";
import fs from "fs";
import { visualizer } from "rollup-plugin-visualizer";
import progress from "vite-plugin-progress";

export default defineConfig(({ mode }) => {
  const viteEnv = loadEnv(mode, "./");
  const optimizeDepsElementPlusIncludes = ["element-plus/es"];
  fs.readdirSync("node_modules/element-plus/es/components").map((dirname) => {
    fs.access(`node_modules/element-plus/es/components/${dirname}/style/css.mjs`, (err) => {
      if (!err) {
        optimizeDepsElementPlusIncludes.push(`element-plus/es/components/${dirname}/style/css`);
      }
    });
  });
  return {
    optimizeDeps: {
      include: optimizeDepsElementPlusIncludes
    },
    base: viteEnv.VITE_BASE,
    server: {
      port: 8888,
      // 显示IP地址
      host: true,
      // 端口占用直接退出
      strictPort: true,
      // 启动后是否自动打开浏览器
      open: false,
      // 确保支持 HMR
      watch: {
        usePolling: true
      }
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url))
      }
    },
    plugins: [
      vue(),
      visualizer(),
      VueDevTools(),
      UnoCss(),
      //reloadUnoCSS(),
      topLevelAwait({
        promiseExportName: "__tla",
        promiseImportName: (i: any) => `__tla_${i}`
      }),
      AutoImport({
        dirs: ["src/api/", "src/stores/", "src/utils/", "src/hooks/", "src/i18n"],
        // 需要去解析的文件
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/ // .md
        ],
        // imports 指定自动引入的包位置（名）
        imports: ["vue", "pinia", "vue-router", "@vueuse/core"],
        // 生成相应的自动导入json文件。
        eslintrc: {
          // 启用
          enabled: true,
          // 生成自动导入json文件位置
          filepath: "./.eslintrc-auto-import.json",
          // 全局属性值
          globalsPropValue: true
        },
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        // imports 指定组件所在目录，默认为 src/components
        dirs: ["src/components/"],
        // 需要去解析的文件
        include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
        resolvers: [ElementPlusResolver({}), VueHooksPlusResolver()]
      }),
      legacy({
        targets: ["defaults", "ie >= 11", "chrome 49"], //需要兼容的目标列表，可以设置多个
        additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
        renderLegacyChunks: true,
        polyfills: [
          "es.symbol",
          "es.array.filter",
          "es.promise",
          "es.promise.finally",
          "es/map",
          "es/set",
          "es.array.for-each",
          "es.object.define-properties",
          "es.object.define-property",
          "es.object.get-own-property-descriptor",
          "es.object.get-own-property-descriptors",
          "es.object.keys",
          "es.object.to-string",
          "web.dom-collections.for-each",
          "esnext.global-this",
          "esnext.string.match-all"
        ]
      }),
      progress(),
      mode === "analyze" ? visualizer({ open: true }) : undefined
    ],
    css: {
      preprocessorOptions: {
        scss: {
          // 加载全局样式，使用scss特性
          additionalData: '@import "./src/assets/scss/globalVariable.scss";'
        }
      }
    },
    build: {
      minify: "terser",
      outDir: "dist",
      assetsDir: "static/assets",
      sourcemap: false,
      // 规定触发警告的 chunk 大小，消除打包大小超过500kb警告
      chunkSizeWarningLimit: 2000
    }
  };
});
